import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate'

export type ChartHistoryItem = {
  id: string
  requirement: string
  imageUrl: string
  timestamp: number
}

export const useChartStore = defineStore(
  'chart',
  () => {
    const history = ref<ChartHistoryItem[]>([])
    const isGenerating = ref(false)
    const currentImageUrl = ref('')

    const addToHistory = (requirement: string, imageUrl: string) => {
      const newItem: ChartHistoryItem = {
        id: Date.now().toString(),
        requirement,
        imageUrl,
        timestamp: Date.now()
      }
      
      history.value.unshift(newItem)
      
      // 保持历史记录最多20条
      if (history.value.length > 20) {
        history.value = history.value.slice(0, 20)
      }
    }

    const clearHistory = () => {
      history.value = []
      currentImageUrl.value = ''
    }

    const removeHistoryItem = (id: string) => {
      const index = history.value.findIndex(item => item.id === id)
      if (index > -1) {
        history.value.splice(index, 1)
      }
    }

    const setGenerating = (status: boolean) => {
      isGenerating.value = status
    }

    const setCurrentImageUrl = (url: string) => {
      currentImageUrl.value = url
    }

    return {
      history,
      isGenerating,
      currentImageUrl,
      addToHistory,
      clearHistory,
      removeHistoryItem,
      setGenerating,
      setCurrentImageUrl
    }
  },
  {
    persist: {
      key: 'witdata-chart-store',
      storage: localStorage,
      paths: ['history'],
    } as PersistenceOptions
  }
) 